﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using CoreEx.Services;
using LinFu.IoC;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using CoreEx.Common.Extensions;
using LinFu.IoC.Configuration;

namespace CoreEx.Wcf.Server
{
    /// <summary>
    /// A custom <see cref="ServiceHostFactory"/> that enables usage of the <see cref="IServiceContainer"/> 
    /// </summary>
    /// <remarks>
    /// By using a service container to provide service instances, there is no need to reference the actual implementation anywhere.    
    /// </remarks>
    /// <example>
    /// The following example shows how to configure a web server to use an <b>ICustomerManager</b> service instance.    
    /// Notice that there is no reference to the actual implementation of the <b>ICustomerManager</b> interface.
    /// <code>
    /// <![CDATA[<%@ ServiceHost Language="C#"  Debug="true" Service="MyApplication.MyServiceLayer.ICustomerManager" 
    /// Factory ="CoreEx.Server.ServiceContainerServiceHostFactory" %>]]>
    /// </code>
    /// </example>
    public class ServiceContainerServiceHostFactory : ServiceHostFactory
    {
        /// <summary>
        /// The <see cref="IServiceContainer"/> that provides service instances
        /// </summary>
        private static readonly IServiceContainer _serviceContainer;

        /// <summary>
        /// Initializes the <see cref="IServiceContainer"/> instance.
        /// </summary>
        static ServiceContainerServiceHostFactory()
        {           
            _serviceContainer = ServiceLocator.Container;
        }


        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            
            
            Type type = Type.GetType(constructorString);
            return base.CreateServiceHost(constructorString, baseAddresses);
        }

        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var serviceHost = _serviceContainer.GetService<ServiceHost>(new object[] { serviceType, baseAddresses });
            return serviceHost;
        }
        
    }
}